import { PlusOutlined, GroupOutlined, QuestionCircleOutlined } from '@ant-design/icons';
import { Button, Divider, message, Input, Select, Modal } from 'antd';
import React, { useState, useRef } from 'react';
import debounce  from 'lodash.debounce';
import { PageContainer } from '@ant-design/pro-layout';
import ProTable, { ProColumns, ActionType } from '@ant-design/pro-table';
import OrgTypeModel from './components/OrgTypeModel';
import AddOrgModel from './components/AddOrgModel';
import SetOrgModel from './components/SetOrgModel';
import OrgTypeListComponent from './components/OrgTypeListComponent';
import ParentOrgListComponent from './components/ParentOrgListComponent';
import { OrgItem } from './data.d';
import { orgList, addOrg, updateOrg, delOrg } from './service';

const { Search } = Input;
const { Option } = Select;

const children = [];
for (let i = 10; i < 36; i++) {
  children.push(<Option key={i.toString(36) + i}>{i.toString(36) + i}</Option>);
}

const OrganizationList: React.FC<{}> = () => {
  const [typeModalVisible, handleTypeModalVisible] = useState<boolean>(false);
  const [orgModalVisible, handleOrgModalVisible] = useState<boolean>(false);
  const [setOrgModalVisible, handleSetOrgModalVisible] = useState<boolean>(false);
  const [deleteModalVisible, handleDeleteModalVisible] = useState<boolean>(false);
  const [disabled, handleDisabled] = useState<boolean>(true);//机构类型是否可用，根据上级机构
  // const [parentOrgId, setParentOrgId] = useState<number>(10000);//【机构类型】与【上级机构】联动
  const [formValues, setFormValues] = useState<OrgItem>();
  const actionRef = useRef<ActionType>();
  const orgId = JSON.parse(localStorage.getItem("user")).orgId;
  //添加
  const addOrgCommand = (param: OrgItem) => {
    new Promise((resolve, reject) => {
      addOrg(param)
        .then((res) => {
          if (res.code === 200) {
            const hide = message.success('添加成功');
            handleOrgModalVisible(false);
            if (actionRef.current) {
              hide();
              actionRef.current.reload();
            }
            resolve(true);
          } else {
            message.error('添加失败，'+res.message);
            resolve(false);
          }
        })
        .catch((error) => {
          message.error('添加失败');
          reject(error);
        });
    });
  }
  //编辑
  const updateOrgComment = (param: OrgItem) => {
    new Promise((resolve, reject) => {
      updateOrg(param)
        .then((res) => {
          if (res.code === 200) {
            const hide = message.success('保存成功');
            handleOrgModalVisible(false);
            if (actionRef.current) {
              hide();
              actionRef.current.reload();
            }
            resolve(true);
          }else if(res.code === 4501){
            message.error("父机构ID不存在",1);
            resolve(false);
          }else if(res.code === 4502){
            message.error("一级机构同名",1);
            resolve(false);
          }else if(res.code === 4503){
            message.error("机构ID不存在",1);
            resolve(false);
          } else if(res.code === 4504){
            message.error("机构类型错误",1);
            resolve(false);
          }else {
            message.error('保存失败');
            resolve(false);
          }
        })
        .catch((error) => {
          message.error('保存失败');
          reject(error);
        });
    });
  }
   //添加/编辑弹出框 确定按钮
   const handleUpdate = async (values: OrgItem) => {
    if (values != null && values != undefined) {
      let id = values.id;
      if(id){//编辑
        updateOrgComment(values);
      }else{//添加
        addOrgCommand(values);
      }
    }
  };

  //删除--删除弹出框
  const delConfirm = (id: number) => {
    Modal.confirm({
      visible: deleteModalVisible,
      title: '确定删除',
      icon: <QuestionCircleOutlined />,
      content: '此机构永久删除',
      okText: '确认',
      cancelText: '取消',
      onOk: () => {
        return new Promise((resolve, reject) => {
          delOrg(id)
            .then((res) => {
              if (res.code === 200) {
                const hide = message.success('删除成功');
                handleDeleteModalVisible(false);
                hide();
                actionRef.current?.reload?.();
                resolve(true);
              }else {
                message.error('删除失败,'+res.message);
                resolve(false);
              }
            })
            .catch((error) => {
              message.error('删除失败');
              reject(error);
            });
        });
      },
    });
  };

  //重置监听
  const onReset = () =>{
    handleDisabled(true);
  }

  const columns: ProColumns<OrgItem>[] = [
    {
      title: '序号',
      dataIndex: 'index',
      valueType: 'text',
      hideInSearch: true, 
    },
    {
      title: '机构ID',
      dataIndex: 'id',
      valueType: 'text',
      hideInSearch: true, 
    },
    {
      title: '机构名',
      dataIndex: 'orgName',
      renderFormItem: (_, { type, defaultRender, ...rest }, form) => {
        if (type === 'form') {
          return null;
        }
        const status = form.getFieldValue('state');
        if (status !== 'open') {
          return (
            <Search
              placeholder="请输入机构名称"
              onSearch={debounce(value=>{form.submit()}, 500)}
              onChange={debounce(value=>{form.submit()}, 500)}
              style={{ width: 200 }}
            />
          );
        }
        return defaultRender(_);
      },
      valueType: 'text',
    },
    {
      title: '上级机构',
      dataIndex: 'parentOrgId',
      renderFormItem: (_, { type, defaultRender, ...rest }, form) => {
        if (type === 'form') {
          return null;
        }
        const status = form.getFieldValue('state');
        if (status !== 'open') {
          return (
            <ParentOrgListComponent 
              defaultvalue={-1}
              type="topOrgId"
              selectChange={(value) => {
                form.setFieldsValue({"parentOrgId": value,"orgTypeId":null});
                // setParentOrgId(value);
                if(value){
                  handleDisabled(false);
                }else{
                  handleDisabled(true);
                }
                form.submit();
              }}
              >
            </ParentOrgListComponent>
          );
        }
        return defaultRender(_);
      },
      hideInTable:true,
      valueType: 'text',
    },
    {
      title: '上级机构',
      dataIndex: 'parentOrgName',
      valueType: 'text',
      hideInSearch: true, 
    },
    {
      title: '机构类型',
      dataIndex: 'orgTypeId',
      hideInForm: true,
      renderFormItem: (_, { type, defaultRender, ...rest }, form) => {
        if (type === 'form') {
          return null;
        }
        const status = form.getFieldValue('state');
        const parentOrgId = form.getFieldValue('parentOrgId');
        let value = "";
        if (status !== 'open') {
          return (
            <OrgTypeListComponent 
              defaultvalue={-1}
              value={value}
              disabled={disabled}
              selector={parentOrgId}
              selectChange={(value) => {
                form.setFieldsValue({"orgTypeId": value? value:null});
                form.submit();}}
            >
            </OrgTypeListComponent>
          );
        }
        return defaultRender(_);
      },
      valueType: 'text',
      hideInTable:true,
    },
    {
      title: '机构类型',
      dataIndex: 'orgTypeName',
      valueType: 'text',
      hideInSearch: true, 
    },
    {
      title: '更新时间',
      dataIndex: 'datetime',
      valueType: 'dateTime',
      hideInSearch: true, 
    },
    {
      title: '操作',
      dataIndex: 'option',
      valueType: 'option',
      render: (_, record) => (
        <>
          <a
            onClick={() => {
              handleSetOrgModalVisible(true);
              setFormValues(record);
            }}
          >
            设置
          </a>
          <Divider type="vertical" />
          <a
            disabled={record.id === orgId?true:false}
            onClick={() => {
              handleOrgModalVisible(true);
              setFormValues(record);
            }}
          >
            编辑
          </a>
          <Divider type="vertical" />
          <a  
            disabled={record.id === orgId?true:false}
            onClick={() => {
              delConfirm(record.id);
          }}>删除</a>
        </>
      ),
    },
  ];

  return (
    <PageContainer>
      <ProTable<OrgItem>
        options={false}
        actionRef={actionRef}
        rowKey="key"
        search={{
          labelWidth: 120,
        }}
        onReset={onReset}
        pagination={{ showQuickJumper: true,defaultPageSize: 10 }}
        toolBarRender={() => [
          <Button type="primary" onClick={() => handleTypeModalVisible(true)}>
          <GroupOutlined /> 机构类型管理
        </Button>,
          <Button type="primary" onClick={() => {
            handleOrgModalVisible(true);
            setFormValues("");
          }}>
            <PlusOutlined /> 新建机构
          </Button>,
        ]}
        request={(params, sorter, filter) => orgList({ ...params, sorter, filter })}
        columns={columns}
      />
      <OrgTypeModel
        onCancel={() =>{
            handleTypeModalVisible(false);
            actionRef.current?.reload?.();
          }
        }
        onSubmit={()=>{
            handleTypeModalVisible(false);
            actionRef.current?.reload?.();
          }
        }
        modalVisible={typeModalVisible}
        > 
      </OrgTypeModel>
      <AddOrgModel 
        onSubmit={handleUpdate}
        onCancel={() => handleOrgModalVisible(false)} 
        modalVisible={orgModalVisible}
        values={formValues}
        >
      </AddOrgModel>
      <SetOrgModel
        onCancel={() => handleSetOrgModalVisible(false)} 
        onSubmit={()=>{
          actionRef.current?.reload?.();
        }}
        modalVisible={setOrgModalVisible}
        values={formValues}
        >
      </SetOrgModel>
    </PageContainer>
  );
};

export default OrganizationList;
